﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using GTA.ExceptionHandling;

namespace GTA.BusinessLogic
{
    public class GTA
    {
        #region Local Objects
        //public static Byte[] CryptKey = new Byte[] { 34, 56, 23, 77, 42, 45, 78, 8 };
        #endregion

        public void StartTeamSystemInstance()
        {
            new ResourceAccess.GTA().StartTeamSystemInstance();
        }
        public List<BusinessEntity.Task> ListArchitectureTasks(BusinessEntity.TaskFilter filter, BusinessEntity.UserManagement.User loggedUser)
        {
            return new ResourceAccess.GTA().ListArchitectureTasks(filter, loggedUser);
        }
        public string GetArchitectureTasksHTMLFormat(List<BusinessEntity.Task> tasksFound)
        {
            String template = BusinessLogic.Properties.Resources.TemplateScenarios;

            template = template.Replace("[data_hora]", DateTime.Now.ToString("dd/MM/yyyy - HH:mm:ss"));

            Int32 idxIni = template.IndexOf("[line_template]");
            Int32 idxEnd = template.IndexOf("[fim_line_template]") + 19;

            String lineTemplate = template.Substring(idxIni, idxEnd - idxIni);

            if (tasksFound != null && tasksFound.Count > 0)
            {
                foreach (BusinessEntity.Task itemTask in tasksFound)
                {
                    String lineValues = lineTemplate;
                    lineValues = lineValues.Replace("[id]", itemTask.ID.ToString());
                    lineValues = lineValues.Replace("[projeto]", itemTask.Project != null ? itemTask.Project.Name : String.Empty);
                    lineValues = lineValues.Replace("[titulo]", itemTask.Title);
                    lineValues = lineValues.Replace("[inicio_previsto]", itemTask.ScheduleEstimatedStart != DateTime.MinValue ? itemTask.ScheduleEstimatedStart.ToString("dd/MM/yyyy") : String.Empty);
                    lineValues = lineValues.Replace("[termino_previsto]", itemTask.ScheduleEstimatedEnd != DateTime.MinValue ? itemTask.ScheduleEstimatedEnd.ToString("dd/MM/yyyy") : String.Empty);
                    lineValues = lineValues.Replace("[inicio]", itemTask.ScheduleRealizedStart != DateTime.MinValue ? itemTask.ScheduleRealizedStart.ToString("dd/MM/yyyy") : String.Empty);
                    lineValues = lineValues.Replace("[termino]", itemTask.ScheduleRealizedEnd != DateTime.MinValue ? itemTask.ScheduleRealizedEnd.ToString("dd/MM/yyyy") : String.Empty);
                    lineValues = lineValues.Replace("[tipo]", itemTask.Category != null ? itemTask.Category.Description : String.Empty);
                    lineValues = lineValues.Replace("[status]", itemTask.State != null ? itemTask.State.Description : String.Empty);
                    lineValues = lineValues.Replace("[razao]", itemTask.Reason);
                    lineValues = lineValues.Replace("[responsavel]", itemTask.DesignedTo != null ? itemTask.DesignedTo.Name : String.Empty);
                    lineValues = lineValues.Replace("[horas_estimadas]", itemTask.ScheduleEstimatedHours != Int32.MinValue ? itemTask.ScheduleEstimatedHours.ToString() : String.Empty);
                    lineValues = lineValues.Replace("[line_template]", "");
                    lineValues = lineValues.Replace("[fim_line_template]", "");
                    template = template.Replace(lineTemplate, lineValues + lineTemplate);
                }
            }

            template = template.Replace(lineTemplate, String.Empty);

            return template;
        }
        public string GetArchitectureTasksHTMLFormat(BusinessEntity.TaskFilter filter, BusinessEntity.UserManagement.User loggedUser)
        {
            return GetArchitectureTasksHTMLFormat(ListArchitectureTasks(filter, loggedUser));
        }
        public void ExportXlsArchitectureTasks(List<BusinessEntity.Task> tasksFound, string pathXlsFile)
        {
            String htmlFormat = GetArchitectureTasksHTMLFormat(tasksFound);
            StreamWriter writer = new StreamWriter(pathXlsFile, false, Encoding.UTF8);
            writer.Write(htmlFormat);
            writer.Close();
        }
        public string GetPerformanceHTMLFormat(BusinessEntity.TaskFilter filter, BusinessEntity.UserManagement.User loggedUser)
        {
            return GetPerformanceHTMLFormat(ListPerformance(filter, loggedUser));
        }
        public string GetPerformanceHTMLFormat(List<BusinessEntity.TaskPerformance> performancesFound)
        {
            String template = BusinessLogic.Properties.Resources.TemplateArchitecturePerformance;

            template = template.Replace("[data_hora]", DateTime.Now.ToString("dd/MM/yyyy - HH:mm:ss"));

            Int32 idxIni = template.IndexOf("[line_template]");
            Int32 idxEnd = template.IndexOf("[fim_line_template]") + 19;

            String lineTemplate = template.Substring(idxIni, idxEnd - idxIni);

            if (performancesFound != null && performancesFound.Count > 0)
            {
                foreach (BusinessEntity.TaskPerformance itemPerformance in performancesFound)
                {
                    String lineValues = lineTemplate;
                    lineValues = lineValues.Replace("[Arquiteto]", itemPerformance.Architect != null ? itemPerformance.Architect.Name : String.Empty);
                    lineValues = lineValues.Replace("[Entregas]", itemPerformance.Delivered.ToString());
                    lineValues = lineValues.Replace("[Atrasos]", itemPerformance.Overdue.ToString());
                    lineValues = lineValues.Replace("[percentual]", itemPerformance.Percentual.ToString("N2"));
                    lineValues = lineValues.Replace("[line_template]", "");
                    lineValues = lineValues.Replace("[fim_line_template]", "");
                    template = template.Replace(lineTemplate, lineValues + lineTemplate);
                }
            }

            template = template.Replace(lineTemplate, String.Empty);

            return template;
        }
        public void ExportXlsPerformance(List<BusinessEntity.TaskPerformance> performancesFound, string pathXlsFile)
        {
            String htmlFormat = GetPerformanceHTMLFormat(performancesFound);
            StreamWriter writer = new StreamWriter(pathXlsFile, false, Encoding.UTF8);
            writer.Write(htmlFormat);
            writer.Close();
        }
        public List<BusinessEntity.Project> ListTeamProjects()
        {
            return new ResourceAccess.GTA().ListTeamProjects();
        }
        public List<BusinessEntity.TaskField> ListFieldDefinitions()
        {
            return new ResourceAccess.GTA().ListFieldDefinitions();
        }
        public List<BusinessEntity.UserManagement.User> ListTeamSystemUsers(BusinessEntity.Project project)
        {
            return new ResourceAccess.GTA().ListTeamSystemUsers(project);
        }
        public List<BusinessEntity.UserManagement.User> ListTeamSystemUsers(List<BusinessEntity.Project> selectedProjects)
        {
            return new ResourceAccess.GTA().ListTeamSystemUsers(selectedProjects);
        }
        public List<BusinessEntity.TaskDomain> ListStates()
        {
            return new ResourceAccess.GTA().ListStates();
        }
        public List<BusinessEntity.TaskDomain> ListStatesTeamSystem(BusinessEntity.UserManagement.User loggedUser)
        {
            return new ResourceAccess.GTA().ListStatesTeamSystem(loggedUser);
        }
        public List<BusinessEntity.TaskDomain> ListCategories()
        {
            return new ResourceAccess.GTA().ListCategories();
        }
        public List<BusinessEntity.TaskDomain> ListCategoriesTeamSystem(BusinessEntity.UserManagement.User loggedUser)
        {
            return new ResourceAccess.GTA().ListCategoriesTeamSystem(loggedUser);
        }
        public List<BusinessEntity.TaskDomain> ListTaskHistoryGeneralClassifications()
        {
            return new ResourceAccess.GTA().ListTaskHistoryGeneralClassifications();
        }
        private BusinessEntity.TaskFilter ManageFilterUserRestriction(BusinessEntity.UserManagement.User loggedUser, BusinessEntity.TaskFilter filter)
        {
            if (loggedUser.UserProfile == BusinessEntity.UserManagement.Profiler.External ||
                loggedUser.UserProfile == BusinessEntity.UserManagement.Profiler.User)
            {
                if (filter.Project != null && filter.Project.Count > 0)
                    filter.Project.RemoveAll(it => !loggedUser.UserProjects.Exists(itp => itp.Name.CompareTo(it.Name) == 0));
                else
                {
                    filter.Project = new List<BusinessEntity.Project>();
                    filter.Project.AddRange(loggedUser.UserProjects);
                }

                if (loggedUser.UserProfile == BusinessEntity.UserManagement.Profiler.User)
                {
                    filter.DesignedTo = new List<BusinessEntity.UserManagement.User>();
                    filter.DesignedTo.Add(loggedUser);
                }
            }
            return filter;
        }
        public List<BusinessEntity.InformativeSummaryProjects> ListInformativeSummaryProjects(BusinessEntity.UserManagement.User loggedUser, BusinessEntity.TaskFilter filter)
        {
            List<BusinessEntity.InformativeSummaryProjects> summary = null;

            filter = ManageFilterUserRestriction(loggedUser, filter);
            List<BusinessEntity.Task> tasks = this.ListArchitectureTasks(filter, loggedUser);
            if (tasks != null && tasks.Count > 0)
            {
                summary = new List<BusinessEntity.InformativeSummaryProjects>();

                var result = from unit in tasks
                             group unit by unit.Project.Name into valores
                             select valores;

                foreach (IGrouping<String, BusinessEntity.Task> itemLookup in result.ToList())
                {
                    if (!String.IsNullOrEmpty(itemLookup.Key))
                        summary.Add(new BusinessEntity.InformativeSummaryProjects(itemLookup.Key));
                }

                foreach (BusinessEntity.InformativeSummaryProjects itemSummary in summary)
                    itemSummary.TaskQuantity = tasks.Count(itemTask => itemTask.Project.Name.CompareTo(itemSummary.ProjectName) == 0);

                if (summary != null)
                    summary.Sort(new Comparison<BusinessEntity.InformativeSummaryProjects>(
                        delegate(BusinessEntity.InformativeSummaryProjects summary1, BusinessEntity.InformativeSummaryProjects summary2)
                        {
                            return summary1.ProjectName.CompareTo(summary2.ProjectName);
                        }));
            }

            return summary;
        }
        public List<BusinessEntity.InformativeSummaryArchitects> ListInformativeSummaryArchitects(BusinessEntity.UserManagement.User loggedUser, BusinessEntity.TaskFilter filter)
        {
            List<BusinessEntity.InformativeSummaryArchitects> summary = null;
            filter = ManageFilterUserRestriction(loggedUser, filter);
            List<BusinessEntity.Task> tasks = this.ListArchitectureTasks(filter, loggedUser);
            if (tasks != null && tasks.Count > 0)
            {
                summary = new List<BusinessEntity.InformativeSummaryArchitects>();

                var result = from unit in tasks
                             group unit by unit.DesignedTo.Name into valores
                             select valores;

                foreach (IGrouping<String, BusinessEntity.Task> itemLookup in result.ToList())
                {
                    if (!String.IsNullOrEmpty(itemLookup.Key))
                        summary.Add(new BusinessEntity.InformativeSummaryArchitects(itemLookup.Key));
                }

                foreach (BusinessEntity.InformativeSummaryArchitects itemSummary in summary)
                    itemSummary.TaskQuantity = tasks.Count(itemTask => itemTask.DesignedTo.Name.CompareTo(itemSummary.ArchitectName) == 0);

                if (summary != null)
                    summary.Sort(new Comparison<BusinessEntity.InformativeSummaryArchitects>(
                        delegate(BusinessEntity.InformativeSummaryArchitects summary1, BusinessEntity.InformativeSummaryArchitects summary2)
                        {
                            return summary1.ArchitectName.CompareTo(summary2.ArchitectName);
                        }));
            }

            return summary;
        }
        public List<BusinessEntity.InformativeSummaryStates> ListInformativeSummaryStates(BusinessEntity.UserManagement.User loggedUser, BusinessEntity.TaskFilter filter)
        {
            List<BusinessEntity.InformativeSummaryStates> summary = null;
            filter = ManageFilterUserRestriction(loggedUser, filter);
            List<BusinessEntity.Task> tasks = this.ListArchitectureTasks(filter, loggedUser);
            if (tasks != null && tasks.Count > 0)
            {
                summary = new List<BusinessEntity.InformativeSummaryStates>();

                var result = from unit in tasks
                             group unit by unit.State.Description into valores
                             select valores;

                foreach (IGrouping<String, BusinessEntity.Task> itemLookup in result.ToList())
                {
                    if (!String.IsNullOrEmpty(itemLookup.Key))
                        summary.Add(new BusinessEntity.InformativeSummaryStates(itemLookup.Key));
                }

                foreach (BusinessEntity.InformativeSummaryStates itemSummary in summary)
                    itemSummary.TaskQuantity = tasks.Count(itemTask => itemTask.State.Description.CompareTo(itemSummary.StateDescription) == 0);

                if (summary != null)
                    summary.Sort(new Comparison<BusinessEntity.InformativeSummaryStates>(
                        delegate(BusinessEntity.InformativeSummaryStates summary1, BusinessEntity.InformativeSummaryStates summary2)
                        {
                            return summary1.StateDescription.CompareTo(summary2.StateDescription);
                        }));
            }
            return summary;
        }
        public List<BusinessEntity.InformativeSummaryCategories> ListInformativeSummaryCategories(BusinessEntity.UserManagement.User loggedUser, BusinessEntity.TaskFilter filter)
        {
            List<BusinessEntity.InformativeSummaryCategories> summary = null;
            filter = ManageFilterUserRestriction(loggedUser, filter);
            List<BusinessEntity.Task> tasks = this.ListArchitectureTasks(filter, loggedUser);
            if (tasks != null && tasks.Count > 0)
            {
                summary = new List<BusinessEntity.InformativeSummaryCategories>();

                var result = from unit in tasks
                             group unit by unit.Category.Description into valores
                             select valores;

                foreach (IGrouping<String, BusinessEntity.Task> itemLookup in result.ToList())
                {
                    if (!String.IsNullOrEmpty(itemLookup.Key))
                        summary.Add(new BusinessEntity.InformativeSummaryCategories(itemLookup.Key));
                }

                foreach (BusinessEntity.InformativeSummaryCategories itemSummary in summary)
                    itemSummary.TaskQuantity = tasks.Count(itemTask => itemTask.Category.Description.CompareTo(itemSummary.CategoryDescription) == 0);

                if (summary != null)
                    summary.Sort(new Comparison<BusinessEntity.InformativeSummaryCategories>(
                        delegate(BusinessEntity.InformativeSummaryCategories summary1, BusinessEntity.InformativeSummaryCategories summary2)
                        {
                            return summary1.CategoryDescription.CompareTo(summary2.CategoryDescription);
                        }));
            }
            return summary;
        }
        public List<BusinessEntity.ArchitectDisponibility> ListArchitectDisponibility(BusinessEntity.TaskFilter filter, BusinessEntity.UserManagement.User loggedUser)
        {
            List<BusinessEntity.UserManagement.User> users = null;

            if (loggedUser.UserProfile != BusinessEntity.UserManagement.Profiler.User)
            {
                users = ListUsers(new BusinessEntity.UserManagement.UserFilter());
                if (users != null && users.Count > 0)
                {
                    users.RemoveAll(it => it.UserProfile != BusinessEntity.UserManagement.Profiler.Master &&
                                          it.UserProfile != BusinessEntity.UserManagement.Profiler.User);

                    if (filter.DesignedTo != null && filter.DesignedTo.Count > 0)
                        users.RemoveAll(it => filter.DesignedTo.Find(flt => flt.Name.CompareTo(it.Name) == 0) == null);
                }
            }
            else if (loggedUser.UserProfile == BusinessEntity.UserManagement.Profiler.User)
                users = ListUsers(new BusinessEntity.UserManagement.UserFilter() { Name = loggedUser.Name });

            List<BusinessEntity.ArchitectDisponibility> disponibilities = null;
            List<BusinessEntity.Task> tasks = this.ListArchitectureTasks(filter, loggedUser);

            if (tasks != null)
                tasks.RemoveAll(it => it.State.Description.ToLowerInvariant().CompareTo("cancelado") == 0);

            if (users != null)
            {
                disponibilities = new List<BusinessEntity.ArchitectDisponibility>();
                foreach (BusinessEntity.UserManagement.User itemUser in users)
                {
                    BusinessEntity.ArchitectDisponibility itemDisponibility = new BusinessEntity.ArchitectDisponibility();
                    itemDisponibility.Architect = itemUser;
                    if (tasks != null)
                        itemDisponibility.Tasks = tasks.FindAll(itemTask => itemTask.DesignedTo.Name.CompareTo(itemUser.Name) == 0);
                    disponibilities.Add(itemDisponibility);
                }
            }

            if (disponibilities != null)
            {
                disponibilities.Sort(new Comparison<BusinessEntity.ArchitectDisponibility>(delegate(BusinessEntity.ArchitectDisponibility disponibility1, BusinessEntity.ArchitectDisponibility disponibility2)
                {
                    return disponibility1.Architect.Name.CompareTo(disponibility2.Architect.Name);
                }));
            }

            return disponibilities;
        }
        public List<BusinessEntity.TaskPerformance> ListPerformance(BusinessEntity.TaskFilter filter, BusinessEntity.UserManagement.User loggedUser)
        {
            List<BusinessEntity.TaskPerformance> performances = null;
            List<BusinessEntity.Task> tasks = ListArchitectureTasks(filter, loggedUser);

            if (tasks != null && tasks.Count > 0)
            {
                tasks.RemoveAll(it => it.State.Description.ToLowerInvariant().CompareTo("cancelado") == 0);

                performances = new List<BusinessEntity.TaskPerformance>();

                var result = from unit in tasks
                             group unit by unit.DesignedTo.Name into valores
                             select valores;

                foreach (IGrouping<String, BusinessEntity.Task> itemLookup in result.ToList())
                {
                    if (!String.IsNullOrEmpty(itemLookup.Key))
                    {
                        BusinessEntity.TaskPerformance itemPerformance = new BusinessEntity.TaskPerformance();
                        itemPerformance.Architect = new BusinessEntity.UserManagement.User(itemLookup.Key);

                        Int32 totalTasks = tasks.Count<BusinessEntity.Task>(item =>
                                                                item.DesignedTo.Name.CompareTo(itemLookup.Key) == 0);

                        itemPerformance.Delivered = tasks.Count<BusinessEntity.Task>(item =>
                                                                item.DesignedTo.Name.CompareTo(itemLookup.Key) == 0 &&
                                                                item.State != null &&
                                                                item.State.Description.ToLowerInvariant().CompareTo("finalizado") == 0 &&
                                                                item.ScheduleRealizedEnd != DateTime.MinValue);

                        itemPerformance.Overdue = tasks.Count<BusinessEntity.Task>(item =>
                                                                item.DesignedTo.Name.CompareTo(itemLookup.Key) == 0 &&
                                                                item.State != null &&
                                                                item.State.Description.ToLowerInvariant().CompareTo("finalizado") == 0 &&
                                                                (item.ScheduleRealizedEnd != DateTime.MinValue &&
                                                                 item.ScheduleEstimatedEnd.CompareTo(item.ScheduleRealizedEnd) < 0));

                        if (itemPerformance.Delivered > 0)
                            itemPerformance.Percentual = (itemPerformance.Overdue * 100) / itemPerformance.Delivered;

                        performances.Add(itemPerformance);
                    }
                }
            }

            if (performances != null)
            {
                performances.Sort(new Comparison<BusinessEntity.TaskPerformance>(delegate(BusinessEntity.TaskPerformance performance1, BusinessEntity.TaskPerformance performance2)
                {
                    return performance1.Architect.Name.CompareTo(performance2.Architect.Name);
                }));
            }

            return performances;
        }
        public List<BusinessEntity.Group> ListGroups()
        {
            return new ResourceAccess.GTA().ListGroups();
        }
        public void SaveGroup(BusinessEntity.Group group)
        {
            ResourceAccess.GTA ra = new ResourceAccess.GTA();
            if (group.ID == 0 || group.ID == Int32.MinValue)
                ra.SaveGroup(group);
            else
                ra.UpdateGroup(group);
        }
        public void DeleteGroup(int groupID)
        {
            List<BusinessEntity.UserManagement.User> usersUsingGroup = ListUsers(new BusinessEntity.UserManagement.UserFilter() { GroupID = groupID });
            if (usersUsingGroup != null && usersUsingGroup.Count > 0)
                throw new BusinessException("Existem usuários associado ao grupo, este não pode ser excluído!");

            new ResourceAccess.GTA().DeleteGroup(groupID);
        }
        public BusinessEntity.UserManagement.User GetUser(Int32 userID)
        {
            return new ResourceAccess.GTA().GetUser(userID);
        }
        public List<BusinessEntity.UserManagement.User> ListUsers(BusinessEntity.UserManagement.UserFilter filter)
        {
            return new ResourceAccess.GTA().ListUsers(filter);
        }
        public List<BusinessEntity.UserManagement.User> ListUsers(List<BusinessEntity.Project> selectedProjects)
        {
            return new ResourceAccess.GTA().ListUsers(selectedProjects);
        }
        public List<BusinessEntity.Project> GetUserProjects(int userID)
        {
            return new ResourceAccess.GTA().GetUserProjects(userID);
        }
        public List<DateTime> GetUserAdditionalDays(int userID)
        {
            return new ResourceAccess.GTA().GetUserAdditionalDays(userID);
        }
        public List<BusinessEntity.UserManagement.UserAbsences> GetUserAbsences(int userID)
        {
            return new ResourceAccess.GTA().GetUserAbsences(userID);
        }
        public void SaveUser(BusinessEntity.UserManagement.User user)
        {
            ResourceAccess.GTA ra = new ResourceAccess.GTA();
            if (user.ID == 0 || user.ID == Int32.MinValue)
                ra.SaveUser(user);
            else
                ra.UpdateUser(user);
        }
        public void DeleteUser(int userID)
        {
            new ResourceAccess.GTA().DeleteUser(userID);
        }
        public void ChangeUserPassword(int userID, string newPassword)
        {
            new ResourceAccess.GTA().ChangeUserPassword(userID, newPassword);
        }
        public BusinessEntity.UserManagement.User AuthenticateUser(string userLogin, string userPassword)
        {
            ResourceAccess.GTA ra = new ResourceAccess.GTA();
            List<BusinessEntity.UserManagement.User> users = ra.ListUsers(new BusinessEntity.UserManagement.UserFilter() { Login = userLogin });
            return users != null ? users.Find(it => it.Login.CompareTo(userLogin) == 0 &&
                Cryptography.Util.DESCryptographer.Decrypt(it.Password).CompareTo(Cryptography.Util.DESCryptographer.Decrypt(userPassword)) == 0) : null;
        }
        public bool CheckUserFirstAccess(int userID)
        {
            return new ResourceAccess.GTA().CheckUserFirstAccess(userID);
        }
        public void UpdateUserFirstAccess(int userID, bool state)
        {
            new ResourceAccess.GTA().UpdateUserFirstAccess(userID, state);
        }
        public string GetHolidaysHTMLFormat(BusinessEntity.Configuration.Holidays holidays)
        {
            String template = BusinessLogic.Properties.Resources.TemplateHolidays;

            template = template.Replace("[data_hora]", DateTime.Now.ToString("dd/MM/yyyy - HH:mm:ss"));

            Int32 idxIni = template.IndexOf("[line_template]");
            Int32 idxEnd = template.IndexOf("[fim_line_template]") + 19;

            String lineTemplate = template.Substring(idxIni, idxEnd - idxIni);

            if (holidays != null && holidays.Holiday != null && holidays.Holiday.Count > 0)
            {
                foreach (DateTime itemHoliday in holidays.Holiday)
                {
                    String lineValues = lineTemplate;
                    lineValues = lineValues.Replace("[Data]", itemHoliday.ToString("dd/MM/yyyy"));
                    lineValues = lineValues.Replace("[line_template]", "");
                    lineValues = lineValues.Replace("[fim_line_template]", "");
                    template = template.Replace(lineTemplate, lineValues + lineTemplate);
                }
            }

            template = template.Replace(lineTemplate, String.Empty);

            return template;
        }
        public void ExportHolidays(BusinessEntity.Configuration.Holidays holidays, string pathXlsFile)
        {
            String htmlFormat = GetHolidaysHTMLFormat(holidays);
            StreamWriter writer = new StreamWriter(pathXlsFile, false, Encoding.UTF8);
            writer.Write(htmlFormat);
            writer.Close();
        }
        public List<BusinessEntity.TaskHistory> ListTaskHistory(BusinessEntity.UserManagement.User taskUser, BusinessEntity.Task task)
        {
            return new ResourceAccess.GTA().ListTaskHistory(taskUser, task, Int32.MinValue, Int32.MinValue);
        }
        public List<BusinessEntity.TaskDomain> ListChangeRequestResults()
        {
            return new ResourceAccess.GTA().ListChangeRequestResults();
        }
        public void SaveChangeRequestResult(BusinessEntity.TaskDomain changeRequestResult)
        {
            ResourceAccess.GTA ra = new ResourceAccess.GTA();
            if (changeRequestResult.ID == 0 || changeRequestResult.ID == Int32.MinValue)
                ra.SaveChangeRequestResult(changeRequestResult);
            else
                ra.UpdateChangeRequestResult(changeRequestResult);
        }
        public void DeleteChangeRequestResult(int changeRequestResultID)
        {
            ResourceAccess.GTA ra = new ResourceAccess.GTA();
            List<BusinessEntity.TaskHistory> history = ra.ListTaskHistory(null, null, changeRequestResultID, Int32.MinValue);
            if (history != null && history.Count > 0)
                throw new BusinessException("A Change Request Result está em uso e não pode ser excluída\r\n");

            ra.DeleteChangeRequestResult(changeRequestResultID);
        }
        public void SaveTaskHistory(BusinessEntity.Task task, BusinessEntity.UserManagement.User taskUser, BusinessEntity.TaskHistory history)
        {
            ResourceAccess.GTA ra = new ResourceAccess.GTA();
            if (history.ID == 0 || history.ID == Int32.MinValue)
                ra.SaveTaskHistory(task, taskUser, history);
            else
                ra.UpdateTaskHistory(task, taskUser, history);
        }
        public void DeleteTaskHistory(int historyID)
        {
            new ResourceAccess.GTA().DeleteTaskHistory(historyID);
        }
        public string GetTaskHistoryHTMLFormat(List<BusinessEntity.TaskHistory> historyList)
        {
            String template = BusinessLogic.Properties.Resources.TemplateTaskHistory;

            template = template.Replace("[data_hora]", DateTime.Now.ToString("dd/MM/yyyy - HH:mm:ss"));

            Int32 idxIni = template.IndexOf("[line_template]");
            Int32 idxEnd = template.IndexOf("[fim_line_template]") + 19;

            String lineTemplate = template.Substring(idxIni, idxEnd - idxIni);
            TimeSpan totalTime = new TimeSpan();

            if (historyList != null && historyList.Count > 0)
            {
                foreach (BusinessEntity.TaskHistory itemHistory in historyList)
                {
                    TimeSpan dateInterval = itemHistory.EndDate.Subtract(itemHistory.StartDate);

                    String lineValues = lineTemplate;
                    lineValues = lineValues.Replace("[Nome]", itemHistory.Name);
                    lineValues = lineValues.Replace("[Start_Date]", itemHistory.StartDate.ToString("dd/MM/yyyy HH:mm"));
                    lineValues = lineValues.Replace("[End_Date]", itemHistory.EndDate.ToString("dd/MM/yyyy HH:mm"));
                    lineValues = lineValues.Replace("[Horas_dia]", itemHistory.HoursDay.ToString());
                    lineValues = lineValues.Replace("[Tempo_Total]", (itemHistory.EndDate.Date.CompareTo(itemHistory.StartDate.Date) > 0 ? Convert.ToString(itemHistory.EndDate.Date.Subtract(itemHistory.StartDate.Date).Days * itemHistory.HoursDay) : dateInterval.Hours.ToString().PadLeft(2, '0')) + ":" + itemHistory.EndDate.TimeOfDay.Subtract(itemHistory.StartDate.TimeOfDay).Minutes.ToString().PadLeft(2, '0'));
                    lineValues = lineValues.Replace("[Tipo]", itemHistory.HistoryType.ToString());
                    lineValues = lineValues.Replace("[line_template]", "");
                    lineValues = lineValues.Replace("[fim_line_template]", "");
                    template = template.Replace(lineTemplate, lineValues + lineTemplate);

                    //if (itemHistory.EndDate.Date.CompareTo(itemHistory.StartDate.Date) > 0)
                    //    totalTime = totalTime.Add(new TimeSpan(itemHistory.EndDate.Date.Subtract(itemHistory.StartDate.Date).Days * itemHistory.HoursDay, 0, 0));
                    //else
                    //    totalTime = totalTime.Add(itemHistory.EndDate.Subtract(itemHistory.StartDate));
                    totalTime = totalTime.Add(GetTaskHistoryTotalTime(itemHistory));
                }
            }

            template = template.Replace("[tempo_Total]", (totalTime.Days > 0 ? Convert.ToString((totalTime.Days * 24) + totalTime.Hours) : totalTime.Hours.ToString().PadLeft(2, '0'))
                + ":" + totalTime.Minutes.ToString());
            template = template.Replace(lineTemplate, String.Empty);

            return template;
        }
        public TimeSpan GetTaskHistoryTotalTime(BusinessEntity.TaskHistory itemHistory)
        {
            if (itemHistory.EndDate.Date.CompareTo(itemHistory.StartDate.Date) > 0)
                return new TimeSpan(itemHistory.EndDate.Date.Subtract(itemHistory.StartDate.Date).Days * itemHistory.HoursDay, 0, 0);
            else
                return itemHistory.EndDate.Subtract(itemHistory.StartDate);
        }
        public void ExportXlsTaskHistory(List<BusinessEntity.TaskHistory> historyList, string pathXlsFile)
        {
            String htmlFormat = GetTaskHistoryHTMLFormat(historyList);
            StreamWriter writer = new StreamWriter(pathXlsFile, false, Encoding.UTF8);
            writer.Write(htmlFormat);
            writer.Close();
        }
        public BusinessEntity.TaskComment GetTaskComment(int taskID, int userID)
        {
            return new ResourceAccess.GTA().GetTaskComment(taskID, userID);
        }
        public void SaveTaskComment(BusinessEntity.Task task, int userID)
        {
            ResourceAccess.GTA ra = new ResourceAccess.GTA();
            if (task.Comment.ID == 0 || task.Comment.ID == Int32.MinValue)
                ra.SaveTaskComment(task, userID);
            else
                ra.UpdateTaskComment(task.Comment);
        }
        public List<BusinessEntity.TaskDomain> ListChangeRequestMotivations()
        {
            return new ResourceAccess.GTA().ListChangeRequestMotivations();
        }
        public void SaveChangeRequestMotivation(BusinessEntity.TaskDomain changeRequestMotivation)
        {
            ResourceAccess.GTA ra = new ResourceAccess.GTA();
            if (changeRequestMotivation.ID == 0 || changeRequestMotivation.ID == Int32.MinValue)
                ra.SaveChangeRequestMotivation(changeRequestMotivation);
            else
                ra.UpdateChangeRequestMotivation(changeRequestMotivation);
        }
        public void DeleteChangeRequestMotivation(int motivationID)
        {
            ResourceAccess.GTA ra = new ResourceAccess.GTA();
            List<BusinessEntity.TaskHistory> history = ra.ListTaskHistory(null, null, Int32.MinValue, motivationID);
            if (history != null && history.Count > 0)
                throw new BusinessException("O Motivo da Change Request está em uso e não pode ser excluído\r\n");

            ra.DeleteChangeRequestMotivation(motivationID);
        }
        public void SaveCategories(List<BusinessEntity.TaskDomain> categories)
        {
            ResourceAccess.GTA ra = new ResourceAccess.GTA();
            if (categories != null && categories.Count > 0)
                categories.ForEach(it => ra.SaveCategory(it));
        }
        public void DeleteCategory(int categoryID)
        {
            new ResourceAccess.GTA().DeleteCategory(categoryID);
        }
        public void SaveStates(List<BusinessEntity.TaskDomain> states)
        {
            ResourceAccess.GTA ra = new ResourceAccess.GTA();
            if (states != null && states.Count > 0)
                states.ForEach(it => ra.SaveState(it));
        }
        public void DeleteState(int stateID)
        {
            new ResourceAccess.GTA().DeleteState(stateID);
        }
        public List<BusinessEntity.TaskHistoryChangeRequestReport> ListTaskHistoryChangeRequestMotivationReport(BusinessEntity.TaskHistoryFilter filter)
        {
            ResourceAccess.GTA ra = new ResourceAccess.GTA();
            List<BusinessEntity.TaskHistoryChangeRequestReport> list = ra.ListTaskHistoryChangeRequestMotivationReport(filter);
            if (list != null && list.Count > 0)
            {
                foreach (BusinessEntity.TaskHistoryChangeRequestReport item in list)
                    CalculateTaskHistoryTotalTime(item);
            }
            return list;
        }
        public List<BusinessEntity.TaskHistoryChangeRequestReport> ListTaskHistoryChangeRequestResultReport(BusinessEntity.TaskHistoryFilter filter)
        {
            ResourceAccess.GTA ra = new ResourceAccess.GTA();
            List<BusinessEntity.TaskHistoryChangeRequestReport> list = ra.ListTaskHistoryChangeRequestResultReport(filter);
            if (list != null && list.Count > 0)
            {
                foreach (BusinessEntity.TaskHistoryChangeRequestReport item in list)
                    CalculateTaskHistoryTotalTime(item);
            }
            return list;
        }
        public List<BusinessEntity.TaskHistoryReport> ListTaskHistoryReport(BusinessEntity.TaskHistoryFilter filter)
        {
            ResourceAccess.GTA ra = new ResourceAccess.GTA();
            List<BusinessEntity.TaskHistoryReport> list = ra.ListTaskHistoryReport(filter);
            if (list != null && list.Count > 0)
            {
                foreach (BusinessEntity.TaskHistoryReport item in list)
                    CalculateTaskHistoryTotalTime(item);
            }
            return list;
        }
        private static void CalculateTaskHistoryTotalTime(BusinessEntity.TaskHistoryReport item)
        {
            TimeSpan totalTime = new TimeSpan();
            if (item.EndDate.Date.CompareTo(item.StartDate.Date) > 0)
                totalTime = new TimeSpan(item.EndDate.Date.Subtract(item.StartDate.Date).Days * item.HoursDay, 0, 0);
            else
                totalTime = item.EndDate.Subtract(item.StartDate);
            item.TotalHours = (totalTime.Days > 0 ? (totalTime.Days * 24) + totalTime.Hours : totalTime.Hours);
            item.TotalMinutes = totalTime.Minutes;
        }
        public void UpdateTaskData(BusinessEntity.Task task, BusinessEntity.UserManagement.User loggedUser)
        {
            new ResourceAccess.GTA().UpdateTaskData(task, loggedUser);
        }
        public List<BusinessEntity.UserManagement.Functionality> ListProfilerFunctionalities(BusinessEntity.UserManagement.Profiler profiler)
        {
            return new ResourceAccess.GTA().ListProfilerFunctionalities(profiler);
        }
        public void SaveProfilerFunctionalities(List<BusinessEntity.UserManagement.Functionality> functinoalities, BusinessEntity.UserManagement.Profiler profiler)
        {
            new ResourceAccess.GTA().SaveProfilerFunctionalities(functinoalities, profiler);
        }
        public string GetTasksListAlertHTMLFormat(List<global::GTA.BusinessEntity.Task> tasks)
        {
            String resultHtml = String.Empty;
            String template = BusinessLogic.Properties.Resources.TemplateAlertTasksList;

            Int32 idxIni = template.IndexOf("[line_template]");
            Int32 idxEnd = template.IndexOf("[fim_line_template]") + 19;

            String lineTemplate = template.Substring(idxIni, idxEnd - idxIni);

            if (tasks != null && tasks.Count > 0)
            {
                foreach (BusinessEntity.Task itemTask in tasks)
                {
                    String lineValues = lineTemplate;
                    lineValues = lineValues.Replace("[id]", itemTask.ID.ToString());
                    lineValues = lineValues.Replace("[titulo]", itemTask.Title);
                    lineValues = lineValues.Replace("[inicio_previsto]", itemTask.ScheduleEstimatedStart != DateTime.MinValue ? itemTask.ScheduleEstimatedStart.ToString("dd/MM/yyyy") : String.Empty);
                    lineValues = lineValues.Replace("[termino_previsto]", itemTask.ScheduleEstimatedEnd != DateTime.MinValue ? itemTask.ScheduleEstimatedEnd.ToString("dd/MM/yyyy") : String.Empty);
                    lineValues = lineValues.Replace("[line_template]", "");
                    lineValues = lineValues.Replace("[fim_line_template]", "");
                    template = template.Replace(lineTemplate, lineValues + lineTemplate);
                }
                template = template.Replace(lineTemplate, String.Empty);
                resultHtml = template;
            }

            return resultHtml;
        }
        public void SaveTaskHistoryGeneralClassification(BusinessEntity.TaskDomain classification)
        {
            ResourceAccess.GTA ra = new global::GTA.ResourceAccess.GTA();
            if (classification.ID == 0 || classification.ID == Int32.MinValue)
                ra.SaveTaskHistoryGeneralClassification(classification);
            else
                ra.UpdateTaskHistoryGeneralClassification(classification);
        }
        public void DeleteTaskHistoryGeneralClassification(int id)
        {
            new ResourceAccess.GTA().DeleteTaskHistoryGeneralClassification(id);
        }
    }
}
